package com.ourhealth.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.ourhealth.entity.Result;
import com.ourhealth.pojo.Menu;
import com.ourhealth.pojo.User;
import com.ourhealth.service.MainService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.security.Principal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("main")
public class MainController {
    @Reference
    private MainService mainService;
    @RequestMapping("load")
    public Result load(HttpServletRequest request){
        String s = currentUserNameSimple(request);
        User u = mainService.findUserByUserName(s);
        List<Menu> menus = mainService.load(u);
        Map<String,Object> map = new HashMap<>();
        map.put("username",u.getUsername());
        map.put("menus",menus);
        return new Result(true,"",map);
    }

    //获取security中的登陆信息
    @RequestMapping(value = "/username")
    public String currentUserNameSimple(HttpServletRequest request) {
        Principal principal = request.getUserPrincipal();
        return principal.getName();
    }

    @PreAuthorize("hasAuthority('MENU_ADD')")
    @RequestMapping("append")
    public Result append(@RequestBody Map<String,String> map){
        String parentMenusId = map.get("id");
        String linkUrl = map.get("linkUrl");
        String name = map.get("name");

        Menu menu = new Menu();
        menu.setName(name);
        menu.setLinkUrl(linkUrl);
        menu.setParentMenuId(Integer.valueOf(parentMenusId));

        mainService.addMenu(menu);

        return new Result(true,"");
    }

    @PreAuthorize("hasAuthority('MENU_DELETE')")
    @RequestMapping("remove")
    public Result remove(int id){
        mainService.remove(id);
        return new Result(true,"");
    }

}
